package com.bcxj.servicepassengeruser.service;

import com.bcxj.internalcommon.constant.CommonStatusEnum;
import com.bcxj.internalcommon.dto.ResponseResult;
import com.bcxj.internalcommon.entity.PassengerUser;
import com.bcxj.servicepassengeruser.mapper.PassengerUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * ClassName: UserService
 * Package: com.bcxj.servicepassengeruser.service
 * Description:
 *
 * @Author BCXJ
 * @Create 2024/9/17 23:39
 * @Version 1.0
 * @Since 1.0
 */
@Service
public class UserService {

    @Autowired
    private PassengerUserMapper userMapper;


    @Transactional
    /**
     * 用户的注册
     * @param passengerPhone
     * @return
     */
    public ResponseResult loginOrRegister(String passengerPhone) {
        // 根据手机号查询用户
        HashMap<String, Object> map = new HashMap<>();
        map.put("passenger_phone", passengerPhone);

        List<PassengerUser> passengerUsers = userMapper.selectByMap(map);

        // 用户存在直接诶返回
        // 注意，没有查到数据 返回的List的size位0，不会为null哦
        if (passengerUsers.size() > 0) {
            return ResponseResult.success("用户已存在");
        }

        // 用户不存在则插入数据
        PassengerUser passengerUser = new PassengerUser();

        passengerUser.setPassengerPhone(passengerPhone);
        passengerUser.setPassengerName("user-" + generateRandomString(10));
        passengerUser.setPassengerGender((byte) 0);
        passengerUser.setPassengerPhone(passengerPhone);
        passengerUser.setState((byte) 0);

        LocalDateTime now = LocalDateTime.now();
        passengerUser.setGmtCreate(now);
        passengerUser.setGmtModified(now);

        userMapper.insert(passengerUser);

        return ResponseResult.success("新用户注册成功");
    }



    private static final String ALPHA_NUMERIC_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    private static String generateRandomString(int length) {
        Random random = new Random();
        StringBuilder builder = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            builder.append(ALPHA_NUMERIC_STRING.charAt(random.nextInt(ALPHA_NUMERIC_STRING.length())));
        }
        return builder.toString();
    }


    /**
     * 根据手机号获取用户的信息
     * @param passengerPhone
     * @return
     */
    public ResponseResult getUserInfo(String passengerPhone) {

        Map<String, Object> map = new HashMap<>();
        map.put("passenger_phone", passengerPhone);
        List<PassengerUser> passengerUsers = userMapper.selectByMap(map);

        if(passengerUsers.isEmpty()) {
            return ResponseResult.fail(CommonStatusEnum.USER_NOT_EXIST);
        }

        return ResponseResult.success(passengerUsers.get(0));
    }
}
